//一.express构建服务器
const express = require("express");
const path = require("path");
const mongoose = require("mongoose");
mongoose.connect("mongodb://127.0.0.1/news", err => {
    if (err) {
        return console.log(err)
    }
    console.log("数据库连接成功");
})
// 建立骨架
let schema = mongoose.Schema({
    title: String,
    detail: String,
    addtime: String
})

// 和集合建立关系 
let newsModel = mongoose.model("lists", schema);
let app = express();

//设置views的路径，设置ejs模板引擎  
app.set("views", './views');
app.set("view engine", 'ejs');

//设置静态资源映射
app.use(express.static(path.join(__dirname, "./static")))

app.get('/', async (req, res) => {
    let data = await newsModel.find();
    res.render("index.ejs",{data})
    // res.send("hello");
})

app.get('/detail',async(req,res)=>{
  let {_id} = req.query;
  console.log(_id); // 可以通过 _id 查询到具体的数据
  let [detailData] =  await newsModel.find({_id});  // 通过id查询详细信息 数组中对象结构出来
  console.log(detailData);
  res.render("detail.ejs",{detailData});
})

app.listen(8989)